package _18_剑指OfferII;

import _18_剑指OfferII.datastrcute.ListNode;

public class _021_剑指OfferII删除链表的倒数第n个结点 {

    // 快慢指针
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode slow = head;
        ListNode fast = slow;
        for (int i = 0; i < n; i++) {
            fast = fast.next;
        }

        if (fast == null) {
            return head.next;
        }

        // 快慢指针移动
        while (fast.next != null) {
            slow = slow.next;
            fast = fast.next;
        }

        slow.next = slow.next.next;

        return head;
    }

    private int count = 1;

    private int n;

    // 递归写法
    public ListNode removeNthFromEnd1(ListNode head, int n) {
        this.n = n;
        ListNode listNode = removeNthFromEnd(head);
        if (n == count) return head.next;
        return listNode;
    }


    public ListNode removeNthFromEnd(ListNode head) {
        if (head == null) return head;

        ListNode newHead = removeNthFromEnd(head.next);
        if (count++ == n) {
            head.next = newHead.next;
        }

        return head;
    }

}
